/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/store/';
import {getStore} from '@/util/store'
import router from '@/router/router'
import {
  serialize
} from '@/util/util'
import {
  getToken
} from '@/util/auth'
import {
  Message,
  MessageBox
} from 'element-ui';
import website from '@/config/website';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  Base64
} from 'js-base64';
import { Loading } from 'element-ui';
import { refeshToken } from '@/api/user'

axios.defaults.timeout = 30000;

//请求次数
axios.defaults.retry = 2;

//请求的间隙
axios.defaults.retryDelay = 1000;

//返回其他状态吗
axios.defaults.validateStatus = function(status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
  showSpinner: false
});

let loadingInstance = null;

let printNumbers = 1;
let printUrlFlag = false;
let printUrlConfig = '';
//HTTPrequest拦截
axios.interceptors.request.use(config => {
  // console.log(config,'config')
  if (!config.unProgress) {
    NProgress.start() // start progress bar
  }
  const meta = (config.meta || {});
  const isToken = meta.isToken === false;
  if (config.url.indexOf("?") != -1) {
    config.url = config.url + `&v_ignore=${website.version}`
  } else {
    config.url = config.url + `?v_ignore=${website.version}`
  }
  if(config.url.indexOf('orderPrintingFrequency') > -1) {// 打印次数Url
    printUrlConfig = config;
    printUrlFlag = true;
  }
  if (config.isLoading) {
    loadingInstance = Loading.service({ fullscreen: true });
  }
  config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
  if (getToken() && !isToken) {
    config.headers['Blade-Auth'] = 'bearer ' + getToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
  }
  //headers中配置serialize为true开启序列化
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
  }
  return config
}, error => {
  return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(
  res => {
  const { config } = res
  NProgress.done();
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
  const status = res.data.code || 200;
  const statusWhiteList = website.statusWhiteList || [];
  const message = res.data.msg || '系统更新中';
  const {currentRoute} = router
  //如果在白名单里则自行catch逻辑处理
  if (statusWhiteList.includes(status)) return Promise.reject(res);
  //如果是401则跳转到登录页面 
  if (status === 401) {
    // 二次校验
    store.dispatch('RequestCheck').then(res => {}).catch(() => {
      store.dispatch('FedLogOut').finally(() => router.push({
        path: '/login',
        query: {
          redirect: currentRoute.fullPath
        }
      }));
    })
    return
  }
  if (status === 1001) {
    // 特殊状态，跳转登录页面
    store.dispatch('FedLogOut').then(() => router.push({
      path: '/login',
      query: {
        redirect: currentRoute.fullPath
      }
    }));
  }
  // 如果请求为非200否者默认统一处理
  if (status !== 200) {
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  }
  return res;
}, error => {
  NProgress.done();
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
  if(printUrlFlag) {
    printUrlFlag = false;
    // 若打印次数接口第一次未请求成功，则重新请求两次
    var config = printUrlConfig;
    // If config does not exist or the retry option is not set, reject
    if(!config || !config.retry) return Promise.reject(new Error(error));

    // Set the variable for keeping track of the retry count
    config.__retryCount = config.__retryCount || 0;

    // Check if we've maxed out the total number of retries
    if(config.__retryCount >= config.retry) {
      // Reject with the error
      return Promise.reject(new Error(error));
    }

    // Increase the retry count
    config.__retryCount += 1;

    // Create new promise to handle exponential backoff
    var backoff = new Promise(function(resolve) {
      setTimeout(function() {
        resolve();
      }, config.retryDelay || 1);
    });

    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
      printNumbers += 1;
      // console.log('config',config,printNumbers);
      if(printNumbers == 2) {
        window.ProPrintFlag();
        // Message.warning('网络异常，请重试打印');
        MessageBox.confirm('网络异常，请重试打印', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          showClose: false,// 关闭 ×
          showCancelButton: false,// 取消按钮
          closeOnClickModal: false// 遮罩关闭
        }).then(() => {
          Message.warning('网络异常，请重试打印');
        })
      }
      return axios(config);
    });
  } else {
    printUrlFlag = false;
    return Promise.reject(new Error(error));
  }
})

export default axios;
